<template>
  <div class="app-container">
    <!--部门数据-->
    <el-row :gutter="20">
      <el-col :span="4" :xs="24" v-if="showTree">
        <div class="head-container">
          <el-input
            v-model="deptIdName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptIdOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="showTree?17:20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="用户账号" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户账号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入用户昵称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>


        <el-table v-loading="loading" :data="tagTestList" @selection-change="handleSelectionChange"
                  @row-click="handleRowClick" @select-all="handleSelectAll" ref="table">
          <el-table-column type="selection" width="55" align="center" :selectable="canSelect"/>
          <el-table-column label="用户账号" align="center" prop="userName"/>
          <el-table-column label="用户昵称" align="center" prop="nickName"/>
          <el-table-column label="用户类型" align="center" prop="userType"/>
          <el-table-column label="手机号码" align="center" prop="phonenumber"/>
          <el-table-column label="帐号状态" align="center" prop="status"/>
          <el-table-column label="备注" align="center" prop="remark"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['test:tagTest:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['test:tagTest:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
      <el-col :span="showTree?3:4">
        <div>
          <el-tag
            v-for="(tag,index) in selectedTags"
            :key="index"
            closable
            @close="handleTagClose(tag)"
          >
            {{ tag.userName }}
          </el-tag>
        </div>
      </el-col>

    </el-row>
    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID"/>
        </el-form-item>
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户账号"/>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户昵称"/>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入用户邮箱"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码"/>
        </el-form-item>
        <el-form-item label="头像地址" prop="avatar">
          <el-input v-model="form.avatar" placeholder="请输入头像地址"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="最后登录IP" prop="loginIp">
          <el-input v-model="form.loginIp" placeholder="请输入最后登录IP"/>
        </el-form-item>
        <el-form-item label="最后登录时间" prop="loginDate">
          <el-date-picker clearable
                          v-model="form.loginDate"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择最后登录时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listTagTest, getTagTest, delTagTest, addTagTest, updateTagTest, deptIdTreeSelect} from "@/api/test/tagTest";

export default {
  name: "TagTest",
  props: {
    showTree: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      tagTestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nodeIds: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        userType: undefined,
        email: undefined,
        phonenumber: undefined,
        sex: undefined,
        avatar: undefined,
        password: undefined,
        status: undefined,
        loginIp: undefined,
        loginDate: undefined,
      },
      //树选项
      deptIdOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      deptIdName: undefined,
      selectedTags: [], // 选中的标签集合
      selectData: [[]],
      pageTurn: false,
      selectedRow: null, // 当前选中的表格行
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          {required: true, message: "用户ID不能为空", trigger: "blur"}
        ],
        deptId: [
          {required: true, message: "部门ID不能为空", trigger: "blur"}
        ],
        userName: [
          {required: true, message: "用户账号不能为空", trigger: "blur"}
        ],
        nickName: [
          {required: true, message: "用户昵称不能为空", trigger: "blur"}
        ],
        userType: [
          {required: true, message: "用户类型不能为空", trigger: "change"}
        ],
        email: [
          {required: true, message: "用户邮箱不能为空", trigger: "blur"}
        ],
        phonenumber: [
          {required: true, message: "手机号码不能为空", trigger: "blur"}
        ],
        sex: [
          {required: true, message: "用户性别不能为空", trigger: "change"}
        ],
        avatar: [
          {required: true, message: "头像地址不能为空", trigger: "blur"}
        ],
        password: [
          {required: true, message: "密码不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "帐号状态不能为空", trigger: "change"}
        ],
        loginIp: [
          {required: true, message: "最后登录IP不能为空", trigger: "blur"}
        ],
        loginDate: [
          {required: true, message: "最后登录时间不能为空", trigger: "blur"}
        ],
        remark: [
          {required: true, message: "备注不能为空", trigger: "blur"}
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptIdName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.initialize();
    this.getdeptIdTree();
  },
  methods: {
    async initialize() {
      let response = await listTagTest();
      this.tagTestList = response.rows;
      this.total = response.total;
      this.loading = false;
      //todo
      // this.$nextTick(() => {
      //   this.$refs.table.toggleRowSelection(this.tagTestList[0],true)
      // });
    },
    /** 查询用户信息列表 */
    getList() {
      this.loading = true;
      this.pageTurn = true;
      listTagTest(this.queryParams).then(response => {
        this.tagTestList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.$nextTick(() => {

          this.selectedTags.forEach(item => {
            let index = this.findTagIndex(this.tagTestList, item)
            if (index != -1) {
              this.$refs.table.toggleRowSelection(this.tagTestList[index], true)
            }
          })
          this.pageTurn = false
        });
      });
    },
    handleRowClick(row) {
      // 处理表格行点击事件
      this.$refs.table.toggleRowSelection(row)

    },
    handleTagClose(tag) {
      // 处理标签关闭事件
      let index = this.selectedTags.indexOf(tag);
      if (index !== -1) {
        // 移除标签
        this.selectedTags.splice(index, 1);
        this.$refs.table.toggleRowSelection(tag, false)
      }
      this.selectData.forEach(item => {
        let i = this.findTagIndex(item, tag);
        if (i != -1) {
          item.splice(i, 1)
        }
      })

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        userType: undefined,
        email: undefined,
        phonenumber: undefined,
        sex: undefined,
        avatar: undefined,
        password: undefined,
        status: undefined,
        delFlag: undefined,
        loginIp: undefined,
        loginDate: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询树结构 */
    getdeptIdTree() {
      deptIdTreeSelect().then(response => {
        this.deptIdOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.nodeIds = this.getAllChildrenIds(data.id)
      this.handleQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (!this.selectData[this.queryParams.pageNum]) {
        this.selectData[this.queryParams.pageNum] = []
      }
      if (!this.pageTurn) {
        this.selectData[this.queryParams.pageNum] = selection;
      }
      this.selectedTags = this.selectData.flat(1);
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.pageTurn = false
    },
    handleSelectAll(selection) {
      console.log(selection)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const userId = row.userId || this.ids
      getTagTest(userId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.userId != null) {
            updateTagTest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addTagTest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('"是否确认删除用户信息编号为"' + userIds + '"的数据项？').then(() => {
        this.loading = true;
        return delTagTest(userIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('test/tagTest/export', {
        ...this.queryParams
      }, `tagTest_${new Date().getTime()}.xlsx`)
    },
    getAllChildrenIds(targetId) {
      const result = [];
      let targetNode = this.findNodeById(this.deptIdOptions, targetId);
      if (targetNode) {
        result.push(targetNode.id);
        this.getAllChildrenIdsRecursive(targetNode, result);
      }
      return result;
    },
    getAllChildrenIdsRecursive(node, result) {
      if (node.children) {
        for (let child of node.children) {
          result.push(child.id);
          this.getAllChildrenIdsRecursive(child, result);
        }
      }
    },
    findNodeById(nodes, targetId) {
      for (let node of nodes) {
        if (node.id == targetId) {
          return node
        } else if (node.children) {
          for (let child of node.children) {
            let foundNode = this.findNodeById(node.children, targetId);
            if (foundNode) {
              return foundNode;
            }
          }
        }
      }
    },
    findTagIndex(arr, newObj) {
      let index = arr.findIndex(obj => {
        let keys = Object.keys(obj);
        return keys.every(key => obj[key] === newObj[key]);
      });
      return index;
    },
    canSelect(){
      return this.selectedTags.length < 1;
    }
  }
};
</script>

<style scoped>
.el-tag {
  margin-left: 10px;
  margin-top: 5px;
}

</style>
